package com.mikhailenko.transportMVC.service.es.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mikhailenko.transportMVC.exeption.es.BlockNotFoundException;
import com.mikhailenko.transportMVC.model.es.BlockEntity;
import com.mikhailenko.transportMVC.repository.es.BlockRepository;
import com.mikhailenko.transportMVC.service.es.BlockService;

@Service
public class BlockServiceImpl implements BlockService {

    @Autowired
    private BlockRepository blockRepository;
    
    @Override
    public BlockEntity create(BlockEntity block) {
        BlockEntity createdBlock = block;
        return blockRepository.saveAndFlush(createdBlock);
    }

    @Override
    public BlockEntity delete(int id) throws BlockNotFoundException {
        BlockEntity deletedBlock = blockRepository.findOne(id);
        
        if (deletedBlock == null){
            throw new BlockNotFoundException();
        }
        
        blockRepository.delete(deletedBlock);
        return deletedBlock;
    }

    @Override
    public List<BlockEntity> findAll() {
        return blockRepository.findAll();
    }

    @Override
    public BlockEntity update(BlockEntity block) throws BlockNotFoundException {
        BlockEntity updatedBlock = blockRepository.findOne(block.getId());
        
        if (updatedBlock == null){
            throw new BlockNotFoundException();
        }
        
        updatedBlock.setCountOfInputs(block.getCountOfInputs());
        updatedBlock.setLayer(block.getLayer());
        
        return updatedBlock;
    }

    @Override
    public BlockEntity findById(int id) {
        return blockRepository.findOne(id);
    }

	@Override
	public BlockEntity findByName(String name) {
		return blockRepository.findByName(name);
	}

	@Override
	public List<BlockEntity> findByLayerId(int id) {
		return blockRepository.findByLayerId(id);
	}

}
